{% extends "profile/base.html" %}

{% block title %}文件上传{% endblock %}

{% block content %}
<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <!-- 页面标题 -->
            <div class="text-center mb-5 fade-in">
                <h1 class="display-4 fw-bold text-gradient">文件管理中心</h1>
                <p class="lead text-muted">安全、便捷地上传和管理您的文件</p>
            </div>
            
            <!-- 文件上传卡片 -->
            <div class="card mb-4 fade-in">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cloud-upload-alt me-2"></i>文件上传</h5>
                </div>
                <div class="card-body p-4">
                    <form id="upload-form" method="post" enctype="multipart/form-data" novalidate>
                        <div class="row">
                            <div class="col-md-8 mx-auto">
                                <!-- 文件选择区域 -->
                                <div class="mb-4">
                                    <label for="file" class="form-label">
                                        <i class="fas fa-file-upload me-2"></i>选择文件
                                    </label>
                                    <div class="upload-area" id="upload-area">
                                        <input type="file" class="form-control" id="file" name="file" required style="display: none;">
                                        <div class="upload-text">
                                            <p class="mb-2">点击选择文件或拖拽文件到此处</p>
                                            <p class="text-muted small">支持的文件类型: JPG, PNG, GIF, PDF, TXT, DOC, DOCX (最大 16MB)</p>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">
                                        {{ form.file.errors[0] if form.file.errors else '' }}
                                    </div>
                                </div>
                                
                                <!-- 文件描述 -->
                                <div class="mb-4">
                                    <label for="description" class="form-label">
                                        <i class="fas fa-align-left me-2"></i>文件描述
                                    </label>
                                    <textarea class="form-control" id="description" name="description" rows="3" placeholder="添加文件描述信息（可选）">{{ form.description.data or '' }}</textarea>
                                    <div class="form-text">简短描述您的文件内容，方便日后查找</div>
                                    <div class="invalid-feedback">
                                        {{ form.description.errors[0] if form.description.errors else '' }}
                                    </div>
                                </div>
                                
                                <!-- 公开选项 -->
                                <div class="mb-4">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="is_public" name="is_public" {% if form.is_public.data %}checked{% endif %}>
                                        <label class="form-check-label" for="is_public">
                                            <i class="fas fa-globe me-2"></i>公开文件
                                        </label>
                                    </div>
                                    <div class="form-text">勾选此项将使文件对其他用户可见</div>
                                </div>
                                
                                <!-- 按钮组 -->
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="button" class="btn btn-outline-secondary me-md-2" id="reset-btn">
                                        <i class="fas fa-redo me-2"></i>重置
                                    </button>
                                    <button type="submit" class="btn btn-primary" id="upload-btn">
                                        <i class="fas fa-cloud-upload-alt me-2"></i>上传文件
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- 文件预览区域 -->
            <div class="card mb-4 fade-in" id="preview-container" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-eye me-2"></i>文件预览</h5>
                </div>
                <div class="card-body">
                    <div id="preview-content"></div>
                </div>
            </div>
            
            <!-- 上传历史 -->
            {% if files %}
            <div class="card fade-in">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-history me-2"></i>上传历史</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th><i class="fas fa-file me-2"></i>文件名</th>
                                    <th><i class="fas fa-info-circle me-2"></i>类型</th>
                                    <th><i class="fas fa-hdd me-2"></i>大小</th>
                                    <th><i class="fas fa-clock me-2"></i>上传时间</th>
                                    <th><i class="fas fa-shield-alt me-2"></i>状态</th>
                                    <th><i class="fas fa-cogs me-2"></i>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for file in files %}
                                <tr id="file-{{ file.id }}">
                                    <td>
                                        {% if file.is_image %}
                                        <i class="fas fa-file-image me-2"></i>
                                        {% elif file.is_document %}
                                        <i class="fas fa-file-alt me-2"></i>
                                        {% else %}
                                        <i class="fas fa-file me-2"></i>
                                        {% endif %}
                                        {{ file.filename }}
                                    </td>
                                    <td>{{ file.content_type }}</td>
                                    <td>{{ "%.2f"|format(file.size / 1024) }} KB</td>
                                    <td>{{ file.upload_time.strftime('%Y-%m-%d %H:%M') if file.upload_time else '未知' }}</td>
                                    <td>
                                        {% if file.is_public %}
                                        <span class="badge bg-success">公开</span>
                                        {% else %}
                                        <span class="badge bg-secondary">私有</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="{{ url_for('profile.download_file', file_id=file.id) }}" class="btn btn-outline-primary" title="下载">
                                                <i class="fas fa-download"></i>
                                            </a>
                                            <button type="button" class="btn btn-outline-danger" onclick="deleteFile({{ file.id }})" title="删除">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<style>
.text-gradient {
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.form-switch .form-check-input {
    width: 3em;
    height: 1.5em;
    cursor: pointer;
}

.form-switch .form-check-input:checked {
    background-color: #6a11cb;
    border-color: #6a11cb;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%28255,255,255,1.0%29'/%3e%3c/svg%3e");
}

.upload-text {
    pointer-events: none;
}
</style>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
    $(document).ready(function() {
        // 初始化动画
        $('.fade-in').each(function(index) {
            $(this).delay(100 * index).animate({ opacity: 1 }, 500);
        });
        
        // 文件上传区域点击事件
        $('#upload-area').on('click', function() {
            $('#file').click();
        });
        
        // 拖拽上传功能
        $('#upload-area').on('dragover', function(e) {
            e.preventDefault();
            $(this).addClass('dragover');
        });
        
        $('#upload-area').on('dragleave', function(e) {
            e.preventDefault();
            $(this).removeClass('dragover');
        });
        
        $('#upload-area').on('drop', function(e) {
            e.preventDefault();
            $(this).removeClass('dragover');
            
            const files = e.originalEvent.dataTransfer.files;
            if (files.length > 0) {
                $('#file')[0].files = files;
                $('#file').trigger('change');
            }
        });
        
        // 文件选择预览
        $('#file').on('change', function() {
            const file = this.files[0];
            if (file) {
                // 更新上传区域文本
                $('.upload-text p:first').html(`<i class="fas fa-check-circle text-success me-2"></i>已选择文件: <strong>${file.name}</strong>`);
                
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    const previewContainer = $('#preview-container');
                    const previewContent = $('#preview-content');
                    
                    if (file.type.startsWith('image/')) {
                        previewContent.html(`
                            <div class="text-center">
                                <img src="${e.target.result}" class="img-fluid rounded shadow-sm mb-3" alt="预览" style="max-height: 300px;">
                                <h5>${file.name}</h5>
                                <p class="text-muted">大小: ${(file.size / 1024).toFixed(2)} KB</p>
                            </div>
                        `);
                    } else if (file.type === 'application/pdf') {
                        previewContent.html(`
                            <div class="alert alert-info d-flex align-items-center">
                                <i class="fas fa-file-pdf fa-3x me-3"></i>
                                <div>
                                    <h5 class="alert-heading">PDF文件</h5>
                                    <p class="mb-0">${file.name}</p>
                                    <small>大小: ${(file.size / 1024).toFixed(2)} KB</small>
                                </div>
                            </div>
                        `);
                    } else if (file.type.includes('text') || file.type.includes('document')) {
                        previewContent.html(`
                            <div class="alert alert-info d-flex align-items-center">
                                <i class="fas fa-file-alt fa-3x me-3"></i>
                                <div>
                                    <h5 class="alert-heading">文档文件</h5>
                                    <p class="mb-0">${file.name}</p>
                                    <small>大小: ${(file.size / 1024).toFixed(2)} KB</small>
                                </div>
                            </div>
                        `);
                    } else {
                        previewContent.html(`
                            <div class="alert alert-info d-flex align-items-center">
                                <i class="fas fa-file fa-3x me-3"></i>
                                <div>
                                    <h5 class="alert-heading">文件</h5>
                                    <p class="mb-0">${file.name}</p>
                                    <small>大小: ${(file.size / 1024).toFixed(2)} KB</small>
                                </div>
                            </div>
                        `);
                    }
                    
                    previewContainer.slideDown();
                };
                
                reader.readAsDataURL(file);
            }
        });
        
        // 重置表单
        $('#reset-btn').on('click', function() {
            $('#upload-form')[0].reset();
            $('#preview-container').slideUp();
            $('.upload-text p:first').html('点击选择文件或拖拽文件到此处');
            $('.is-invalid').removeClass('is-invalid');
        });
        
        // 表单提交
        $('#upload-form').on('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = $('#upload-btn');
            const originalText = submitBtn.html();
            
            submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>上传中...');
            
            $.ajax({
                url: $(this).attr('action'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // 显示成功消息
                        const alertDiv = document.createElement('div');
                        alertDiv.className = 'alert alert-success alert-dismissible fade show';
                        alertDiv.innerHTML = `
                            <div class="d-flex align-items-center">
                                <i class="fas fa-check-circle fa-2x me-3"></i>
                                <div>
                                    <h5 class="alert-heading">上传成功!</h5>
                                    ${response.message}
                                </div>
                            </div>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        `;
                        document.querySelector('main').prepend(alertDiv);
                        
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        const alertDiv = document.createElement('div');
                        alertDiv.className = 'alert alert-danger alert-dismissible fade show';
                        alertDiv.innerHTML = `
                            <div class="d-flex align-items-center">
                                <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                                <div>
                                    <h5 class="alert-heading">上传失败</h5>
                                    ${response.message || '上传失败，请重试'}
                                </div>
                            </div>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        `;
                        document.querySelector('main').prepend(alertDiv);
                        
                        if (response.errors) {
                            displayFormErrors(response.errors);
                        }
                    }
                },
                error: function(xhr) {
                    let errorMessage = '上传失败，请重试';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                    
                    // 显示错误消息
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-danger alert-dismissible fade show';
                    alertDiv.innerHTML = `
                        <div class="d-flex align-items-center">
                            <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                            <div>
                                <h5 class="alert-heading">上传失败</h5>
                                ${errorMessage}
                            </div>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    `;
                    document.querySelector('main').prepend(alertDiv);
                },
                complete: function() {
                    submitBtn.prop('disabled', false).html(originalText);
                }
            });
        });
    });
    
    // 显示表单错误
    function displayFormErrors(errors) {
        // 清除之前的错误提示
        $('.is-invalid').removeClass('is-invalid');
        $('.invalid-feedback').remove();
        
        // 显示新的错误提示
        for (const [field, messages] of Object.entries(errors)) {
            const input = $(`#${field}`);
            if (input.length) {
                input.addClass('is-invalid');
                const feedback = $('<div class="invalid-feedback"></div>').text(messages.join(', '));
                input.after(feedback);
            }
        }
    }
</script>
{% endblock %}